/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package view;

import control.Observer;
import control.OrderController;
import database.DatabaseHandler;
import java.awt.CardLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.sql.SQLException;
import java.text.ParseException;
import javax.swing.JOptionPane;
import utility.PageHandler;
import view.panels.MenuPanel;

/**
 *
 * @author Jeppe
 */
public class Webbased extends javax.swing.JApplet implements ActionListener{

    private DatabaseHandler databaseHandler;
    private PageHandler pageHandler;

    //<editor-fold defaultstate="collapsed" desc="WindowInitializing">
    LoginDialog loginDialog;
    MenuPanel menuPanel;

//</editor-fold>
    private void makePanels() {
        loginDialog = new LoginDialog(null, true);
        menuPanel = new MenuPanel(null);
        pageHandler.addPage(menuPanel, "MenuPanel");
    }

    /**
     * Initializes the applet Webbased
     */
    @Override
    public void init() {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Windows".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Webbased.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Webbased.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Webbased.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Webbased.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the applet */
        try {
            java.awt.EventQueue.invokeAndWait(new Runnable() {
                public void run() {
                    initComponents();
                    databaseHandler = DatabaseHandler.getInstance();
                    pageHandler = new PageHandler((CardLayout) cardLayoutPanel.getLayout(), cardLayoutPanel);
                    makePanels();
                    //<editor-fold defaultstate="collapsed" desc="DatabaseLogin">
                    boolean connected = false;
                    try {
                        databaseHandler.openConn("ini.txt");
                        connected = true;
                        System.out.println("Forbindelsen er oprettet med ini.txt");
                    } catch (SQLException ex) {
                        JOptionPane.showMessageDialog(null, "Kunne ikke oprette forbindelse til serveren\nPrøv evt. igen senere. Severen kan være nede", "Forbindelsestimeout", 0);
                    } catch (ClassNotFoundException ex) {
                        JOptionPane.showMessageDialog(null, "Driveren blev ikke fundet.\nKontakt systemadministratoren", "Fejlkode: #202", 0);
                    } catch (ArrayStoreException ex) {
                        JOptionPane.showMessageDialog(null, ex, ex.getClass().getName(), 0);
                    } catch (IOException ex) {
                        System.err.println("Kunne ikke skrive den nye ini-fil.");
                    } catch (ParseException ex) {
                        System.err.println("Fejl ved læsning af inifilen. Login oplysninger er blevet ændret af en bruger.\n" + ex.getMessage());
                    }
                    if (!connected) {
                        try {
                            databaseHandler.openConn(null);
                        } catch (SQLException ex) {
                            JOptionPane.showMessageDialog(null, "Kunne ikke oprette forbindelse til serveren\nPrøv evt. igen senere. Severen kan være nede", "Forbindelsestimeout", 0);
                        } catch (ClassNotFoundException ex) {
                            JOptionPane.showMessageDialog(null, "Driveren blev ikke fundet.\nKontakt systemadministratoren", "Fejlkode: #202", 0);
                        } catch (ArrayStoreException ex) {
                            JOptionPane.showMessageDialog(null, ex, ex.getClass().getName(), 0);
                        } catch (IOException ex) {
                            System.err.println("Kunne ikke skrive den nye ini-fil.");
                        } catch (ParseException ex) {
                            System.err.println("Fejl ved læsning af inifilen. Data passer ikke overens.\n" + ex.getMessage());
                        }
                    }
//</editor-fold>
//                    Observer.getInstance().addListener(this);
                }
            });
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * This method is called from within the init() method to initialize the
     * form. WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        cardLayoutPanel = new javax.swing.JPanel();
        leverandørLabel = new javax.swing.JLabel();
        tekstBannerLabel = new javax.swing.JLabel();
        bannerLabel = new javax.swing.JLabel();
        baggrund = new javax.swing.JLabel();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenu3 = new javax.swing.JMenu();
        loggedAsMenu = new javax.swing.JMenuItem();
        jSeparator2 = new javax.swing.JPopupMenu.Separator();
        skiftBrugerMenuItem = new javax.swing.JMenuItem();
        logindudMenuItem = new javax.swing.JMenuItem();
        jSeparator1 = new javax.swing.JPopupMenu.Separator();
        jMenuItem1 = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();

        getContentPane().setLayout(null);

        cardLayoutPanel.setBorder(new javax.swing.border.MatteBorder(null));
        cardLayoutPanel.setOpaque(false);
        cardLayoutPanel.setLayout(new java.awt.CardLayout());
        getContentPane().add(cardLayoutPanel);
        cardLayoutPanel.setBounds(0, 150, 640, 420);

        leverandørLabel.setFont(new java.awt.Font("Love & Trust", 1, 18)); // NOI18N
        leverandørLabel.setForeground(new java.awt.Color(51, 51, 255));
        leverandørLabel.setText("Leverandør: Madpigerne");
        getContentPane().add(leverandørLabel);
        leverandørLabel.setBounds(430, 80, 210, 30);

        tekstBannerLabel.setFont(new java.awt.Font("Love & Trust", 0, 70)); // NOI18N
        tekstBannerLabel.setForeground(new java.awt.Color(255, 255, 255));
        tekstBannerLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        tekstBannerLabel.setText("MadLugen");
        getContentPane().add(tekstBannerLabel);
        tekstBannerLabel.setBounds(70, 10, 500, 90);

        bannerLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/baggrund1.png"))); // NOI18N
        bannerLabel.setOpaque(true);
        getContentPane().add(bannerLabel);
        bannerLabel.setBounds(0, 0, 640, 130);

        baggrund.setBackground(new java.awt.Color(255, 255, 255));
        baggrund.setOpaque(true);
        getContentPane().add(baggrund);
        baggrund.setBounds(0, 0, 640, 568);

        jMenu1.setText("File");

        jMenu3.setText("Bruger");

        loggedAsMenu.setText("Ikke logget ind");
        loggedAsMenu.setEnabled(false);
        jMenu3.add(loggedAsMenu);
        jMenu3.add(jSeparator2);

        skiftBrugerMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F3, 0));
        skiftBrugerMenuItem.setText("Skift Bruger");
        skiftBrugerMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                skiftBrugerMenuItemActionPerformed(evt);
            }
        });
        jMenu3.add(skiftBrugerMenuItem);

        logindudMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F2, 0));
        logindudMenuItem.setText("Log Ind");
        logindudMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                logindudMenuItemActionPerformed(evt);
            }
        });
        jMenu3.add(logindudMenuItem);

        jMenu1.add(jMenu3);
        jMenu1.add(jSeparator1);

        jMenuItem1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F4, java.awt.event.InputEvent.ALT_MASK));
        jMenuItem1.setText("Afslut");
        jMenu1.add(jMenuItem1);

        jMenuBar1.add(jMenu1);

        jMenu2.setText("Indstillinger");
        jMenuBar1.add(jMenu2);

        setJMenuBar(jMenuBar1);
    }// </editor-fold>//GEN-END:initComponents

    private void skiftBrugerMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_skiftBrugerMenuItemActionPerformed
        if (skiftBrugerMenuItem.isEnabled()) {
            loginDialog.setVisible(true);
        }
    }//GEN-LAST:event_skiftBrugerMenuItemActionPerformed

    private void logindudMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_logindudMenuItemActionPerformed
        if (OrderController.getInstance().getAktivBruger() == null) {
            loginDialog.setVisible(true);
        } else {
            OrderController.getInstance().logOut();
        }
    }//GEN-LAST:event_logindudMenuItemActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel baggrund;
    private javax.swing.JLabel bannerLabel;
    private javax.swing.JPanel cardLayoutPanel;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenu jMenu3;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JPopupMenu.Separator jSeparator1;
    private javax.swing.JPopupMenu.Separator jSeparator2;
    private javax.swing.JLabel leverandørLabel;
    private javax.swing.JMenuItem loggedAsMenu;
    private javax.swing.JMenuItem logindudMenuItem;
    private javax.swing.JMenuItem skiftBrugerMenuItem;
    private javax.swing.JLabel tekstBannerLabel;
    // End of variables declaration//GEN-END:variables

    @Override
    public void actionPerformed(ActionEvent ae) {
        if (ae.getActionCommand().equals("Bruger")) {
            if (OrderController.getInstance().getAktivBruger() != null) {
                loggedAsMenu.setText("Logget ind som " + OrderController.getInstance().getAktivBruger().getFornavn());
                skiftBrugerMenuItem.setEnabled(true);
                logindudMenuItem.setText("Log ud");
            } else {
                loggedAsMenu.setText("Ikke logget ind");
                logindudMenuItem.setText("Log ind");
                skiftBrugerMenuItem.setEnabled(false);
            }
        }
    }
}
